package com.spring;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UDPReceiver {
    public static void main(String[] args) {
        try {
            // 创建 DatagramSocket，指定接收端口
            DatagramSocket socket = new DatagramSocket(9999);
            byte[] receiveData = new byte[1024];
            int totalPackets = 100;
            int receivedCount = 0;

            System.out.println("等待接收数据包...");

            for (int i = 1; i <= totalPackets; i++) {
                // 创建 DatagramPacket 用于接收数据
                DatagramPacket packet = new DatagramPacket(receiveData, receiveData.length);
                // 接收数据包（会阻塞直到收到数据）
                socket.receive(packet);
                String message = new String(packet.getData(), 0, packet.getLength());
                System.out.println("接收到数据包: " + message);
                receivedCount++;
            }

            socket.close();
            System.out.println("总共发送 " + totalPackets + " 个数据包，接收到 " + receivedCount + " 个数据包，丢包数: " + (totalPackets - receivedCount));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}